/* eslint-disable no-underscore-dangle,no-param-reassign */
import { TIMEOUT, ERR_OK, baseURL, STATUS } from "./config";
import axios from "axios";
import statusCode from "./statusCode";
import store from "@/store";
import { getCookie, delCookie } from "@/utils/cookie";

let noLoginFlag = true;
let noLoginFlagTimer = 0;
const request = axios.create({
  baseURL: process.env.NODE_ENV !== "production" ? baseURL.dev : baseURL.prod,
  timeout: TIMEOUT,
});

request.interceptors.request.use((theRequest) => {
  theRequest.headers.common.Authorization =
    getCookie("token") || store.state.login.token || "123";
  if (!theRequest.headers.common.Authorization) {
    const url = theRequest.url;
    if (
      url.indexOf("/auth/logout") === -1 &&
      url.indexOf("/auth/login") === -1 &&
      url.indexOf("/auth/validToken") === -1 &&
      url.indexOf("/video-api") === -1
    ) {
      theRequest.cancelToken = new axios.CancelToken((cancel) => {
        cancel("未登录, 取消请求");
      });
    }
  }
  // 通过iframe进来的, cookie不能放token, 只能通过store里面获取
  if (store.state.login.isIframe) {
    theRequest.headers.common.Authorization = store.state.login.token;
  }
  theRequest.params = { ...theRequest.params, _t: Date.now() };
  return theRequest;
});

request.interceptors.response.use(
  (response) => {
    const { code, message } = response.data;
    if (code === statusCode.SUCCESS) {
      return response.data;
    }
    const error = new Error(message || "访问人数太多，请刷新试试");
    error.code = code;
    error.result = response.data.result;
    if (response.config.url.indexOf("/auth/login")) {
      return response.data;
    }
    throw error;
  },
  (error) => {
    let message = "当前访问人数太多，请刷新试试";
    let code = 500;
    const { response, code: _code } = error;
    if (axios.isCancel(error)) {
      message = "未登录, 取消请求";
    }
    const targetPath = window.location.hash.replace("#", "");
    if (response && response.status) {
      code = response.status;
      // const $router = window.$windowRrouter || router;
      const $router = window.$windowRrouter;
      if (code === statusCode.LOGIN_OVERTIME) {
        message = "登录超时，请重新登录";
        document.cookie = "";
        delCookie("token");
        app.$emit("unLogin");
        // $router.push('/login');
      } else if (code === statusCode.NOT_POWER) {
        message = "无权限操作";
        if (targetPath !== "/") {
          $router.push("/login");
        }
      } else if (code === statusCode.NOT_PATH) {
        message = "接口路径异常";
      } else if (code === statusCode.INTER_ERROR) {
        message = "后端网关服务异常，请重试!";
      } else if (code === statusCode.SERVER_ERROR) {
        // message = '服务异常!';
        if (response.data.message) {
          message = response.data.message;
        } else {
          message = "服务异常!";
        }
      }
    }
    if (_code === statusCode.ECONNABORTED) {
      message = "服务连接超时";
    }
    if (message === "登录超时，请重新登录" || message === "未登录, 取消请求") {
      clearTimeout(noLoginFlagTimer);
      noLoginFlagTimer = setTimeout(() => {
        noLoginFlag = false;
      }, 2000);
      if (!noLoginFlag) {
        noLoginFlag = true;
        store.commit("login/updateLogin", false);
      } else {
        message = "";
      }
    }
    const _error = new Error(message);
    _error.code = code;
    throw _error;
  }
);

export default request;
